/*
 * Relational model rules
 * Author: Nikolay A. Makarov
 */

#include ".\relationalmodel.h"

relationalModel::relationalModel(void)
{
}

relationalModel::~relationalModel(void)
{
}

//Check unique columns name
bool relationalModel::uniqueColumnsRules( vector< vector<char*> > table) {
	for (int col = 0; col < table.size() - 1; col++) {
		if (strcmp(table[col][0], table[col+1][0]) == 0) {
			return false;
		}
	}
	return true;
}

//Check unique strings in the table
bool relationalModel::uniqueStringRules(vector< vector<char*> > table) {
	for (int pos = 0; pos < table[0].size() - 1; pos++) {
		if (table[0][pos] != NULL) {
			int count = pos;
			while (count < table[0].size()-1) {
				if (table[0][count+1] != NULL) {
					if (strcmp(table[0][pos], table[0][count+1]) == 0) {
						return false;
					}
				}
				count++;
			}
		}
	}
	return true;
}
//Check unique type in columns
bool relationalModel::uniqueTypeRules(vector < vector<char*> > table, char* nameOfTable) {
	//TODO: Check for unique type in columns
	datastore2 DS;
	vector< vector<char*> > types;
	types = DS.getColumns(nameOfTable);
	for(int col = 0; col < types.size(); col ++) {
		if ((strcmp(types[col].at(1), "int") == 0) || (strcmp(types[col].at(1), "key") == 0)) {
			
			for(int i = 1; i < table[col].size()-1; i++ ) {
				
				char* end_ptr;
				long val = 0;
				if(table[col].at(i) != NULL) {
					val = strtol(table[col].at(i), &end_ptr, 10);
					if (*end_ptr) {
					dbmsException e;
					e.setMessage("Mismatch types... Check data and try again.");
					throw e;
					}
					if ((val == LONG_MAX || val == LONG_MIN) && errno == ERANGE)
					{	
						dbmsException e;
						e.setMessage("The number is too long... Check data and try again.");
						throw e;
					}
				}
			}
		}
	}
	return true;
}

//Check relational rules for table
bool relationalModel::isTableRelational(vector< vector<char*> > table, char* nameOfTable) {
	if (relationalModel::uniqueStringRules(table) && relationalModel::uniqueColumnsRules(table) && relationalModel::uniqueTypeRules(table, nameOfTable)) {
		return true;
	} else {
		return false;
	}
}